<template>
  <a-select
    v-bind="$attrs"
    :allow-clear="allowClear"
    :value="props.modelValue"
    :placeholder="placeholder"
    :options="options"
    @change="change"
  >
  </a-select>
</template>

<script lang="ts" setup>
import api from '@/api'
import { ref } from 'vue'
import emitter from '@/utils/bus'

let options = ref<any[]>([])

interface SelectProps {
  placeholder?: string
  modelValue: any
  allowClear?: boolean
}

interface SelectEmits {
  (e: 'update:modelValue', value: string | undefined): void
  (e: 'change', value: string | undefined): void
}

const props = withDefaults(defineProps<SelectProps>(), {
  placeholder: '请选择库区名称',
  allowClear: true,
})

const emit = defineEmits<SelectEmits>()

emitter.on('unit-change', (res: any) => {
  if (res.clear) emit('update:modelValue', undefined)
  getOptions(res.value)
})

const getOptions = async (val): Promise<void> => {
  const { data } = await api.facilityLink(1, [val])
  const list = data.data
  list.forEach((item) => {
    item.value = item.ssid
    item.label = item.ssmc
  })
  options.value = list
}

function change(value: any): void {
  emit('update:modelValue', value)
  emit('change', value)
}
</script>

<style lang="less" scoped></style>
